package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.constant.RedisKeyConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.dto.DeviceDataPageReqDto;
import com.zzyl.serve.service.IDeviceService;
import com.zzyl.serve.vo.IotMsgNotifyData;
import com.zzyl.serve.vo.IotMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceDataMapper;
import com.zzyl.serve.domain.DeviceData;
import com.zzyl.serve.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
import java.util.Map;

/**
 * 设备数据Service业务层处理
 * 
 * @author huangqin
 * @date 2025-05-11
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceDataPageReqDto deviceData) {
        LambdaQueryWrapper<DeviceData> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotEmpty(deviceData.getDeviceName())){
            queryWrapper.like(DeviceData::getDeviceName,deviceData.getDeviceName());
        }
        if (ObjectUtil.isNotEmpty(deviceData.getFunctionId())){
            queryWrapper.eq(DeviceData::getFunctionId,deviceData.getFunctionId());
        }
        if (ObjectUtil.isNotEmpty(deviceData.getStartTime())&& ObjectUtil.isNotEmpty(deviceData.getEndTime())){
            queryWrapper.between(DeviceData::getAlarmTime,deviceData.getStartTime(),deviceData.getEndTime());
        }
        return list(queryWrapper);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 批量保存数据
     *
     * @param iotMsgNotifyData
     */
    @Override
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        String iotId = iotMsgNotifyData.getHeader().getDeviceId();
        //1.判断设备是否存在
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId,iotId);
        Device device = deviceService.getOne(queryWrapper);
        if (ObjectUtil.isEmpty(device)){
            throw new BaseException("该设备不存在");
        }
        //2.获取到设备上报的数据，一个设备可以有多个service
        List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();
        services.forEach(service -> {
            Map<String, Object> properties = service.getProperties();
            if (ObjectUtil.isEmpty(properties)){
                return;
            }
            LocalDateTime eventTime =  LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                                              .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                                              .toLocalDateTime();
            
            ArrayList<DeviceData> deviceDataArrayList = new ArrayList<>();
            properties.forEach((key,value)->{
                DeviceData deviceData = new DeviceData();
                deviceData.setIotId(iotId);
                deviceData.setDeviceName(device.getDeviceName());
                deviceData.setProductKey(device.getProductKey());
                deviceData.setProductName(device.getProductName());
                deviceData.setFunctionId(key);
                deviceData.setAccessLocation(device.getBindingLocation());
                deviceData.setLocationType(device.getLocationType());
                deviceData.setPhysicalLocationType(device.getPhysicalLocationType());
                deviceData.setDeviceDescription(device.getDeviceDescription());
                deviceData.setDataValue(value.toString());
                deviceData.setAlarmTime(alarmTime);
                deviceDataArrayList.add(deviceData);
            });
            saveBatch(deviceDataArrayList);
           
            redisTemplate.opsForHash().put(RedisKeyConstants.IOT_DEVICE_LAST_DATA,iotId, JSONUtil.toJsonStr(deviceDataArrayList));
        });
       
    }
}
